package jasypt;

import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 默认API安全处理
 *
 * @author zhangtao
 */
public class SignHandler {

    private Boolean enableSign;
    private Long legalTime;
    private String defaultSecret;
    private LocalWrapStore wrapStore;


    public String getAppSecret(String appKey) {

        String secret = wrapStore.getSecret(appKey);
        if (StringUtils.isEmpty(secret)) {
            return defaultSecret;
        }
        return secret;
    }

    public boolean verifySignature(String appKey, String data, String signatureParam) {
        if (enableSign) {
            AesEncryptHandler wrapSigner = new AesEncryptHandler(getAppSecret(appKey));
            String signature = new String(wrapSigner.encode(data.getBytes()));
            return signatureParam.equals(signature);
        } else {
            return true;
        }
    }

    public void isLegalTime(long timestamp) {
        long diff = TimeUnit.MILLISECONDS.toSeconds(timestamp - System.currentTimeMillis());
        if (Math.abs(diff) > legalTime) {
            throw new IllegalStateException(String.valueOf(diff));
        }
    }

    public void isReplayAttack(String appKey, long timestamp, int nonce, String signature) {
        String sign = wrapStore.getSign(appKey, timestamp, nonce);
        if (signature.equals(sign)) {
            throw new IllegalStateException(String.format("ReplayAttackException, appKey:%s, timestamp:%s, nonce:%s", appKey, timestamp, nonce));
        } else {
            wrapStore.putSign(appKey, timestamp, nonce, signature);
        }
    }
}
